package com.xianniu.ltc.util;

import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * <Spring工具，用于获取Spring容器管理的Bean>
 * @author ZhangYang
 * @date 2021/1/29 14:05
 * @version 1.0.0
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext; // Spring应用上下文环境

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * <根据Bean名称获取Bean>
     * @param name Bean名称
     * @return T
     * @author ZhangYang
     * @date 2021/1/29 14:04
     * @version 1.0.0
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    /**
     * <根据Bean的类型获取Bean>
     * @param clz Bean类型
     * @return T
     * @author ZhangYang
     * @date 2021/1/29 14:04
     * @version 1.0.0
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<?> clz) throws BeansException {
        return (T) applicationContext.getBean(clz);
    }

    public static <T> Map<String, T>  getBeans(Class<?> clz){
        Map<String, T> result = new HashMap<>();
        String[] types = applicationContext.getBeanNamesForType(clz);
        for(String type : types){
            T t = getBean(type);
            result.put(type, t);
        }
        return result;
    }

}
